package com;
/*

                  写字楼里写字间，写字间里程序员；
                  程序人'猿'写程序，又拿程序换酒钱。
                  酒醒只在网上坐，酒醉还来网下眠；
                  酒醉酒醒日复日，网上网下年复年。
                  但愿老死电脑间，不愿鞠躬老板前；
                  奔驰宝马贵者趣，公交自行程序员。
                  别人笑我忒疯癫，我笑自己命太贱；
                  不见满街漂亮妹，哪个归得程序'猿'？
━━━━━━神兽出没━━━━━━
 ┏┓   ┏┓
┏┛┻━━━┛┻┓
┃       ┃
┃   ━   ┃
┃ ┳┛ ┗┳ ┃
┃       ┃
┃   ┻   ┃
┃       ┃
┗━┓   ┏━┛
  ┃   ┃                    神兽保佑, 永无BUG!
  ┃   ┃       Code is far away from bug with the animal protecting
  ┃   ┗━━━┓
  ┃       ┣┓
  ┃       ┏┛
  ┗┓┓┏━┳┓┏┛
   ┃┫┫ ┃┫┫
   ┗┻┛ ┗┻┛
 */

import com.grpc_client.GrpcClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pb.GreeterGrpc;
import pb.HelloRequest;
import pb.HelloResponse;


/**
 * Created by 石头哥哥 on 1/12/16.
 * <p>
 * grpc
 * <p>
 * client
 * <p>
 * comments:
 */
public class HelloWorldClient {



    private final Logger logger = LoggerFactory.getLogger(HelloWorldClient.class);


    /**
     * 作为单例对象
     */
    private static GrpcClient grpcClient;

    /**
     * Construct client connecting to HelloWorld server at {@code host:port}.
     */
    public HelloWorldClient(String host, int port) {
        grpcClient = new GrpcClient(host, port);
    }

    /**
     * do some logic
     * Say hello to server.
     */
    public void greet(String name) {
        try {
            logger.info("Will try to call remote method");

            //build blocking stub (client)----
            GreeterGrpc.GreeterBlockingClient greeterBlockingClient =
                    GreeterGrpc.newBlockingStub(grpcClient.getChannel());
            //builder send data
            HelloRequest request = HelloRequest.newBuilder().setName(name).build();
            for (int i = 0; i != 100000; ++i) {
                //call remote method and return response
                HelloResponse response = greeterBlockingClient.sayHello(request);
                logger.info("Greeting: " + response.getMessage());
                Thread.sleep(1000);
            }
        } catch (RuntimeException e) {
            logger.debug("RPC failed", e);
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Greet server. If provided, the first element of {@code args} is the name to use in the
     * greeting.
     */
    public static void main(String[] args) throws Exception {
        HelloWorldClient client = new HelloWorldClient("localhost", 50051);
        try {
            String user = "PC:测试哈哈哈~~~~";
            client.greet(user);
        } finally {
            grpcClient.shutdown();
        }
    }
}
